﻿using IM.Easy.Core.AppContext;
using IM.Easy.Core.Exceptions;
using IM.Easy.Core.Log;
using IM.Easy.Entity.Log;
using IM.Easy.LogServices.IServices;
using IM.Easy.Core.Extensions;
using Microsoft.AspNetCore.Authentication;
using AMapPlugin;

namespace IM.Easy.Api
{
    public class ExceptionLogger : IExceptionLogger
    {
        private readonly IExceptionLogService exceptionLogService;
        private readonly IRequestTrackingService requestTrackingService;
        private readonly IAmapPlugin amapPlugin;
        public ExceptionLogger(IExceptionLogService exceptionLogService, IRequestTrackingService requestTrackingService, IAmapPlugin amapPlugin)
        {
            this.exceptionLogService = exceptionLogService;
            this.requestTrackingService = requestTrackingService;
            this.amapPlugin = amapPlugin;
        }

        /// <summary>
        /// 记录异常日志
        /// </summary>
        /// <param name="context"></param>
        /// <param name="exception"></param>
        public async Task Log(HttpContext context, Exception exception)
        {
            var clientIp = context.GetClientUserIp();
            var ipInfo = await amapPlugin.GetIpInfo(clientIp);
            //var remoteInfo = context.GetRemoteIpInfo();
            var sysExceptionLog = new SysExceptionLog();
            sysExceptionLog.Type = exception is BisException ? ExceptionEnum.Business : ExceptionEnum.System;
            sysExceptionLog.Msg = exception.Message;
            sysExceptionLog.Trace = exception.StackTrace;
            sysExceptionLog.TraceIdentifier = context.TraceIdentifier;
            sysExceptionLog.Time = DateTime.Now;
            exceptionLogService.Insert(sysExceptionLog);
        }
    }
}
